package com.maxcion.scalelayoutmanager

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper
import kotlin.math.abs

class AlignLeftSnap : SnapHelper() {
    override fun calculateDistanceToFinalSnap(
        layoutManager: RecyclerView.LayoutManager,
        targetView: View
    ): IntArray? {
        val result = IntArray(2)
        if (layoutManager.canScrollHorizontally()) {
            layoutManager.getChildAt(0)?.let { view ->
                val itemWidth = view.measuredWidth
                var viewCenter = (view.left + view.right) / 2
                if (view == targetView) {
                    result[0] = -(itemWidth / 2 - viewCenter)
                } else {
                    viewCenter = targetView.run {
                        left + right / 2
                    }

                    result[0] = (viewCenter - itemWidth / 2)
                }

            }
        }



        return result

    }

    override fun findSnapView(layoutManager: RecyclerView.LayoutManager?): View? {
        layoutManager?.let {
            if (layoutManager.canScrollHorizontally()) {
                layoutManager.getChildAt(0)?.let { view ->
                    val itemWidth = view.measuredWidth
                    return if (abs(view.left) > itemWidth / 2) {
                        layoutManager.getChildAt(1)
                    } else {
                        view
                    }

                }
            }


        }

        return null
    }

    override fun findTargetSnapPosition(
        layoutManager: RecyclerView.LayoutManager?,
        velocityX: Int,
        velocityY: Int
    ): Int {
        return RecyclerView.NO_POSITION
    }
}